package view;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import model.Filter;

import resources.ResourceProvider;

/**
 * This is a Class for filter settings
 *
 */
public class FilterSettingPanel extends JPanel
{
    /**
     * 
     */
    private static final long serialVersionUID = -593600374648403306L;
    
    MailDisplayArea mailDisplayArea;
    
    List<Filter> activeFilters;
    
    int totalNumOfActiveFilters = 0;
    
    /**Constructor for class FiltersettingPanel and initialize the maildisplay area under it
     * @param mailDisplayArea Will display the area with all the fields in it
     */
    public FilterSettingPanel(MailDisplayArea mailDisplayArea)
    {
      this.initialize();
      this.mailDisplayArea = mailDisplayArea;
    }
    
    /**
     * Initialize FilterSettingPanel
     */
    public void initialize()
    {
        TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Filter Settings");
        this.setBorder(title);
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));      
    }
    
    /**
     * load filter and display filter settings in FilterSettingPanel
     */
    public void loadPriorityPanels()
    {
        String user = this.mailDisplayArea.getEmailApplicationView().getController().getUser();
        String filterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, user);

        List<Filter> filterList = this.mailDisplayArea.getEmailApplicationView().getController().requestFiltersFromPersistence(filterPath);        
        
        activeFilters = new LinkedList<Filter>();
        for(Filter filR : filterList)
        {
            if(filR.isEnabled())
            {
                activeFilters.add(filR);
            }   
        }
        
        totalNumOfActiveFilters = activeFilters.size();
        
        for(Filter filT : activeFilters)
        {
            PrioritySettingPanel settingPanel = new PrioritySettingPanel(filT);
            this.add(settingPanel);
        }
                
        this.revalidate();
        this.repaint(); 
    }
    
    /**
     * Reset and reload the filter
     */
    public void resetAndReload()
    {
        this.removeAll();
        this.loadPriorityPanels();
    }
    
    /**
     * This is a class for filter settings
     */
    class PrioritySettingPanel extends JPanel
    {
        /**
         * 
         */
        private static final long serialVersionUID = 3574399440520911276L;
        Filter filter;
        
        /**
         * constructor of PrioritySettingPanel
         * @param filR the filter
         */
        public PrioritySettingPanel(Filter filR)
        {
           this.filter = filR;
           this.initialize();
        }
        
        /**
         * Initialize PrioritySettingPanel
         */
        public void initialize()
        {
            
            TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Priority - " + this.filter.getPriority());
            this.setBorder(title);
            this.setLayout(null);
            
            JLabel filterName = new JLabel("Name of Filter  :");
            filterName.setBounds(new Rectangle(32,14,125,30));
            filterName.setFont(new Font("Times New Roman",Font.PLAIN,18));
            this.add(filterName);
            
            JTextField filterNameTextField = new JTextField();
            filterNameTextField.setBounds(new Rectangle(155,14,400,30));
            filterNameTextField.setText(this.filter.getFileName());
            filterNameTextField.setEditable(false);
            this.add(filterNameTextField);
                    
            JLabel textLabel = new JLabel("Text to Search  :");
            textLabel.setBounds(new Rectangle(32,44,125,30));
            textLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
            this.add(textLabel);
            
            JTextField keywordToSearchTextField = new JTextField();
            keywordToSearchTextField.setBounds(new Rectangle(155,44,400,30));
            keywordToSearchTextField.setText(this.filter.getKeywordToSearch());
            keywordToSearchTextField.setEditable(false);
            this.add(keywordToSearchTextField);
            
            JLabel selectFolderLabel = new JLabel("Folder to Move :");
            selectFolderLabel.setBounds(new Rectangle(32,74,125,30));
            selectFolderLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
            this.add(selectFolderLabel);
            
            
            String userid = FilterSettingPanel.this.mailDisplayArea.getEmailApplicationView().getController().getUser();
            String mailBoxPath = ResourceProvider.getRootFolderPath(ResourceProvider.MAILBOX, userid) + ResourceProvider.getFilePathSeperator();
            
            JTextField selectMoveFolderText = new JTextField();
            selectMoveFolderText.setEditable(false);
            selectMoveFolderText.setText(this.filter.getDestination().replace(mailBoxPath, ""));
            selectMoveFolderText.setBounds(new Rectangle(155,74,130,30));
            selectMoveFolderText.setEditable(false);
            this.add(selectMoveFolderText);
            
            JLabel filterStatusLabel = new JLabel("Set Priority      :");
            filterStatusLabel.setBounds(new Rectangle(32,104,125,30));
            filterStatusLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
            this.add(filterStatusLabel);
            
            Integer[] names = new Integer[totalNumOfActiveFilters];
            for(int n =1; n <= totalNumOfActiveFilters; n++)
            {
                 names[n-1] = n;            
            }
            
            final JComboBox<Integer> combox = new JComboBox<Integer>(names);
            combox.setBounds(new Rectangle(155,104,130,30));
            this.add(combox);
            combox.setSelectedItem(filter.getPriority());
            
            JButton saveButton = new JButton("Save");
            saveButton.setBounds(new Rectangle(205,154,125,30));
            saveButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) 
                {   
                    int originalPriority = filter.getPriority();
                    int prioritySet = (int)combox.getSelectedItem();
                    if( prioritySet!= originalPriority)
                    {
                        if(originalPriority > prioritySet)
                        {
                            for(Filter filR : activeFilters)
                            {
                                if((!filR.equals(filter)) && (filR.getPriority() >= prioritySet) && (filR.getPriority() <= originalPriority))
                                {
                                    filR.setPriority(filR.getPriority() + 1);
                                }   
                            }
                        }
                        else
                        {
                            for(Filter filR : activeFilters)
                            {
                                if((!filR.equals(filter)) && (filR.getPriority() > originalPriority) &&(filR.getPriority() <= prioritySet))
                                {
                                    filR.setPriority(filR.getPriority() - 1);
                                }   
                            }
                        }

                        filter.setPriority(prioritySet);
                        String user = FilterSettingPanel.this.mailDisplayArea.getEmailApplicationView().getController().getUser();
                        String filterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, user);
                        for(Filter filR : activeFilters)
                        {
                            FilterSettingPanel.this.mailDisplayArea.getEmailApplicationView().getController().requestPersistFilter(filR, filterPath);
                        }
                        
                        SwingUtilities.invokeLater(new Runnable() {
                            
                            /*
                             * (non-Javadoc)
                             * @see java.lang.Runnable#run()
                             */
                            public void run() 
                            {
                                FilterSettingPanel.this.resetAndReload();              
                            }
                        });
                        

                    }
                }
             });
            
            this.add(saveButton);
        }
    }

}
